//
//  HistoryTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/27.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "HistoryTableViewController.h"
#import "CarTableCellTableViewCell.h"
#import "BottomBar.h"
#import "Puser.h"
#import <MJRefresh.h>
#import "CarlistCellMode.h"
#import "CarDetailmodel.h"
#import "UserInfoUpdateResde.h"
#import "CarDetailViewController.h"
#import "NoItemView.h"
@interface HistoryTableViewController ()<UITableViewDataSource,UITableViewDelegate,BottomBarBtnClickDelegate,BottombarDataSource>{
    BOOL _isedting;
    BOOL _candelete;
}
@property (nonatomic,strong) BottomBar *bottombar;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) NSMutableArray  *datalist;
@property (nonatomic,weak) NoItemView *notitem;
@end

@implementation HistoryTableViewController
-(UITableView *)tableView{
    if (_tableView==nil) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, XHScreenheight) style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.backgroundColor=bgGarycolor;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
-(NSMutableArray *)datalist{
    if (_datalist==nil) {
        _datalist=[NSMutableArray array];
    }
    return _datalist;
}

-(void)BottomBarAllclick:(BottomBar *)bottombar{
    for (CarlistCellMode *mode in self.datalist) {
        mode.ischecked=bottombar.allselected;
    }
    [self.tableView reloadData];
}

-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(NSInteger)numberofBottobarcount:(BottomBar *)bottombar{
    return self.datalist.count;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 56, 0);
    self.navigationItem.title=@"浏览记录";
    [self setupRight:NO];
     NoItemView *noitem=[NoItemView viewWithType:MYHISTORYTYPE];
    [self.tableView addSubview:noitem];
    _notitem=noitem;
    [self setuptableView];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
}
-(void)BottomBar:(BottomBar *)bottombar otherbtnClick:(NSInteger)index{
    NSLog(@"%ld",index);
    if (index==0) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"正在操作";
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        params[@"user_id"]=[self.user.power integerValue]<5?self.user.user_id:self.user.com_id;
        params[@"type"]=[self.user.power integerValue]<5?@"person":@"company";
        if ([self.user.power integerValue]==8) {
            params[@"pid"]=self.user.parent_id;
        }
        params[@"action"]=@"cancel_history";
        NSMutableArray *IDarray=[NSMutableArray array];
        for (CarlistCellMode *mode in self.datalist) {
            if (mode.ischecked) {
                [IDarray addObject:mode.cardmode.ID];
            }
        }
        params[@"car_id"]=[NSString DataTOjsonString:IDarray];
        
        [PostUitls Post:myhistoryurl parameters:params success:^(id response) {
            UserInfoUpdateResde *resdmode=[UserInfoUpdateResde resdeWithDict:response];
            if ([resdmode.state integerValue]==400) {
                [self.tableView.header beginRefreshing];
                _candelete=NO;
                self.bottombar.btnenable=_candelete;
                self.bottombar.allselected=_candelete;
            }
            hud.labelText=resdmode.msg;
            hud.mode = MBProgressHUDModeText;
            [hud hide:YES afterDelay:1];
        } failure:^(NSError *error) {
            hud.labelText=@"网络错误";
            hud.mode = MBProgressHUDModeText;
        }];
        
    }else{
        _candelete=NO;
        self.bottombar.btnenable=_candelete;
        self.bottombar.allselected=_candelete;
        [self.tableView.header beginRefreshing];
    }
}

-(void)setuptableView{
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    MJRefreshNormalHeader *header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.header=header;
    MJRefreshBackNormalFooter *footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget: self refreshingAction:@selector(loadmoredata)];
    self.tableView.footer=footer;
    [self.tableView.header beginRefreshing];
}
-(void)refresh{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"my_history";
    NSInteger power=[self.user.power integerValue];
    if (power<5) {
        params[@"type"]=@"person";
        params[@"user_id"]=self.user.user_id;
    }else{
        params[@"type"]=@"company";
        params[@"user_id"]=self.user.com_id;
        if (power==8) {
            params[@"pid"]=self.user.parent_id;
        }
    }
    params[@"num"]=Kpagesize;
    
    [PostUitls Post:myhistoryurl parameters:params success:^(id response) {
        NSDictionary *dict=response;
        NSNumber *state=dict[@"state"];
        if ([state integerValue]==400) {
            [self.datalist removeAllObjects];
           
            NSMutableArray *marray=[NSMutableArray array];
            for (NSDictionary *ddict in dict[@"data"]) {
                CarDetailmodel *detail=[CarDetailmodel carWithdict:ddict];
                CarlistCellMode *mode=[[CarlistCellMode alloc]init];
                mode.cardmode=detail;
                
                [marray addObject:mode];
            }
            [self.datalist addObjectsFromArray:marray];
            if (marray.count<[Kpagesize integerValue]) {
                [self.tableView.footer noticeNoMoreData];
            }else{
                [self.tableView.footer resetNoMoreData];
            }
            if (self.datalist.count>0) {
                [self.notitem hide];
            }else{
                [self.notitem show];
            }
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
        }

    } failure:^(NSError *error) {
        [self.tableView.header endRefreshing];    }];
}
-(void)loadmoredata{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"my_history";
    NSInteger power=[self.user.power integerValue];
    if (power<5) {
        params[@"type"]=@"person";
        params[@"user_id"]=self.user.user_id;
    }else{
        params[@"type"]=@"company";
        params[@"user_id"]=self.user.com_id;
        if (power==8) {
            params[@"pid"]=self.user.parent_id;
        }
    }
    params[@"num"]=Kpagesize;
    NSMutableArray *IDarray=[NSMutableArray array];
    
    for (CarlistCellMode *mode in self.datalist) {
        [IDarray addObject:mode.cardmode.ID];
    }
    params[@"page_id"]=[NSString DataTOjsonString:IDarray];
    
    [PostUitls Post:myhistoryurl parameters:params success:^(id response) {
        
        NSDictionary *dict=response;
        NSNumber *state=dict[@"state"];
        if ([state integerValue]==400) {
            
           
            NSMutableArray *marray=[NSMutableArray array];
            for (NSDictionary *ddict in dict[@"data"]) {
                CarDetailmodel *detail=[CarDetailmodel carWithdict:ddict];
               
                CarlistCellMode *mode=[[CarlistCellMode alloc]init];
                mode.cardmode=detail;
                
                [marray addObject:mode];
            }
            [self.datalist addObjectsFromArray:marray];
            if (marray.count<[Kpagesize integerValue]) {
                [self.tableView.footer noticeNoMoreData];
            }else{
                [self.tableView.footer resetNoMoreData];
            }
            
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
        }else{
            [self.tableView.footer endRefreshing];
        }
        
    } failure:^(NSError *error) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        hud.labelText=@"网络错误";
        hud.mode = MBProgressHUDModeText;
        
        hud.margin = 10.f;
        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        [self.tableView.header endRefreshing];
    }];
}

-(void)rightclick{
    _isedting=!_isedting;
    [self setupRight:_isedting];
    [self.tableView reloadData];
}

-(void)setupRight:(BOOL)iseidting{
    if (iseidting) {
        UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
        [self.bottombar show];
        self.navigationItem.rightBarButtonItem=rightitem;
        
    }else{
         [self.bottombar hide];
        self.bottombar.allselected=NO;
        UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
        
        self.navigationItem.rightBarButtonItem=rightitem;
    }
    
    
}


-(BottomBar *)bottombar{
    if (_bottombar==nil) {
        _bottombar=[[BottomBar alloc]initWithBtnTitleArray:@[@"删除"] WithDelegate:self :YES];
        _bottombar.ishwopost=NO;
        _bottombar.datasource=self;
        [_bottombar addInView:self.view];
    }
    return _bottombar;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.datalist.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CarTableCellTableViewCell *cell=[CarTableCellTableViewCell cellWithTableView:tableView];
    CarlistCellMode *mode=self.datalist[indexPath.row];
    cell.isShowEidt=_isedting;
    cell.carcellmode=mode;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CarlistCellMode *mode=self.datalist[indexPath.row];
    return mode.rowheight;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_isedting) {
        CarlistCellMode *mode=self.datalist[indexPath.row];
        mode.ischecked=!mode.ischecked;
        CarTableCellTableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];
        cell.editbtn.selected=!cell.editbtn.selected;

        for (CarlistCellMode *carmode in self.datalist) {
            if (carmode.ischecked) {
                _candelete=YES;
                break;
            }else{
                _candelete=carmode.ischecked;
            }
        }
        self.bottombar.btnenable=_candelete;
    }else{
        CarlistCellMode *mode=self.datalist[indexPath.row];
        CarDetailViewController *cadvc=[CarDetailViewController viewcontroller];
       
        cadvc.ID=mode.cardmode.ID;
        
        [self.navigationController pushViewController:cadvc animated:YES];
    }
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
